package co.yixiang.modules.delay;

import co.yixiang.modules.commom.domain.YxAppdict;
import co.yixiang.modules.commom.service.mapper.YxAppdictMapper;
import co.yixiang.modules.order.domain.YxStoreOrder;
import co.yixiang.modules.order.service.mapper.StoreOrderMapper;
import co.yixiang.utils.RedisUtils;
import co.yixiang.utils.SpringApplicationContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 三十分钟未付款，删除订单
 */
@Component
public class DelayProductWorker implements Runnable {


    @Override
    @Transactional
    public void run() {
        RedisUtils redisUtil= (RedisUtils) SpringApplicationContextHolder.getSpringBean("RedisUtils");
        StoreOrderMapper storeOrderMapper=(StoreOrderMapper) SpringApplicationContextHolder.getSpringBean("StoreOrderMapper");
        YxAppdictMapper yxAppdictMapper=(YxAppdictMapper) SpringApplicationContextHolder.getSpringBean("YxAppdictMapper");
        //获取所有逾期付款订单id key
        YxAppdict spfksj= yxAppdictMapper.findAppdictByCode("spfksj");
        Integer productTime=30;
        if(null !=spfksj){
            productTime=Integer.parseInt(spfksj.getMemo());
        }
        //获取所有逾期付款订单id key
        List<String> products = redisUtil.getLike("product");
        for (String key:products) {
            String orderId =  redisUtil.get(key).toString();
            YxStoreOrder yxStoreOrder=storeOrderMapper.selectById(orderId);
            if(null !=yxStoreOrder){
                //若为待付款
                Calendar instance = Calendar.getInstance();
                instance.setTime(yxStoreOrder.getCreateTime());
                instance.add(Calendar.MINUTE,productTime);
                Date newCreateTime = instance.getTime();
                //若为待付款
                if(0==yxStoreOrder.getStatus() && 0==yxStoreOrder.getIsDel()  && newCreateTime.compareTo(new Date())==-1){
                    //设为已取消
                    storeOrderMapper.updateIsDel(yxStoreOrder.getId());
                    redisUtil.del(key);
                }else if(0==yxStoreOrder.getStatus() && 0==yxStoreOrder.getIsDel()  && new Date().compareTo(newCreateTime)==-1){
                    DelayProductWorker delayOrderWorker=new DelayProductWorker();
                    DelayOrderQueueManager delayOrderQueueManager=DelayOrderQueueManager.getInstance();
                    delayOrderQueueManager.put(delayOrderWorker,(productTime*60*1000+yxStoreOrder.getCreateTime().getTime()-System.currentTimeMillis())/1000, TimeUnit.SECONDS);
                }
            }
        }
    }  
}  